package com.example.tanlee.ocrgraduation.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import com.example.tanlee.ocrgraduation.R;
import com.example.tanlee.ocrgraduation.application.MyApplication;
import com.example.tanlee.ocrgraduation.eventbus.EventBus;
import com.example.tanlee.ocrgraduation.fragment.PictureFragment;
import com.example.tanlee.ocrgraduation.util.StringConstant;
import com.example.tanlee.ocrgraduation.widget.MyToast;
import com.example.tanlee.ocrgraduation.widget.ViewPagerIndicator;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.pedant.SweetAlert.SweetAlertDialog;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

public class MainActivity extends FragmentActivity implements View.OnClickListener {

    protected static final int REQUEST_IMAGE = 100;
    protected static final int REQUEST_STORAGE_READ_ACCESS_PERMISSION = 101;

    /**
     * 处理连按两次退出应用
     */
    private long firstKeyTime = 0;  //第一次按下返回键的时间
    private boolean readyToExit = false; // 注销请求结果已返回，可以完全退出
    private int time = 0; // 计时器
    private boolean isExiting = false; // 信号量，确保注销请求只发一次
    private int countTemp = 0;

    /**
     * float button 控件;
     */
    private FloatingActionsMenu rightLabels;
    private FloatingActionButton firstBtn;
    private FloatingActionButton secondBtn;

    boolean binaryFlag = false;
    private ArrayList<String> mSelectPath;

    private ViewPagerIndicator mIndicator;
    private List<Fragment> mTabContents = new ArrayList<Fragment>();
    private FragmentPagerAdapter mAdapter;
    private ViewPager mViewPager;

    private PictureFragment historyFragment;
    private PictureFragment unprocessedFragment;
    private PictureFragment processedFragment;

    private List<String> mDatas = Arrays.asList("历史图片", "未处理图片", "已处理图片");

    // 调用底层C++文件所必须的文件信息
    static {
        System.loadLibrary("native-lib");
    }

    private void initView() {
        rightLabels = (FloatingActionsMenu) findViewById(R.id.right_labels);
        firstBtn = (FloatingActionButton) findViewById(R.id.float_action_first_btn);
        secondBtn = (FloatingActionButton) findViewById(R.id.float_action_second_btn);
        mIndicator = (ViewPagerIndicator) findViewById(R.id.main_indicator);
        mViewPager = (ViewPager) findViewById(R.id.main_view_pager);
        initIndicatorData();
        //设置Tab上的标题
        mIndicator.setTabItemTitles(mDatas);
        mViewPager.setAdapter(mAdapter);
        //设置关联的ViewPager
        mIndicator.setViewPager(mViewPager, 0);
    }

    private void initListener() {
        firstBtn.setOnClickListener(this);
        secondBtn.setOnClickListener(this);
    }

    private void initIndicatorData() {

        for (String data : mDatas) {
            PictureFragment fragment = PictureFragment.newInstance(null, null);
            mTabContents.add(fragment);
        }

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public int getCount() {
                return mTabContents.size();
            }

            @Override
            public Fragment getItem(int position) {
                return mTabContents.get(position);
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.btn_cinema:
//                //暂时开启相机,只能选择一张照片
//                pickImage();
//                break;
//            case R.id.sample_btn:
//                binaryFlag = !binaryFlag;
//                if(binaryFlag) {
//                    Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(
//                            R.mipmap.android_logo_96)).getBitmap();
//                    int w = bitmap.getWidth(), h = bitmap.getHeight();
//                    int[] pix = new int[w * h];
//                    bitmap.getPixels(pix, 0, w, 0, 0, w, h);
//                    int[] resultPixes = rgb2Gray(pix, h, w);
////                    MyUtil.showBitmap(resultPixes, imageView, w, h);
//                }
//                break;
            case R.id.fab: //悬浮按钮操作
                Snackbar.make(v, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                break;
            case R.id.float_action_first_btn: // 进行同步操作
                showDialog();
                break;
            case R.id.float_action_second_btn: // 进行拍摄图片的操作
                pickImage();
                break;
            default:
                break;
        }
    }

    private void showDialog(){
        final SweetAlertDialog pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText("Loading");
        pDialog.show();
        pDialog.setCancelable(false);
        new CountDownTimer(800 * 7, 800) {
            public void onTick(long millisUntilFinished) {
                // you can change the progress bar color by ProgressHelper every 800 millis
                countTemp ++;
                switch (countTemp){
                    case 0:
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.blue_btn_bg_color));
                        break;
                    case 1:
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.material_deep_teal_50));
                        break;
                    case 2:
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.success_stroke_color));
                        break;
                    case 3:
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.material_deep_teal_20));
                        break;
                    case 4:
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.material_blue_grey_80));
                        break;
                    case 5:
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.warning_stroke_color));
                        break;
                    case 6:
                        pDialog.getProgressHelper().setBarColor(getResources().getColor(R.color.success_stroke_color));
                        break;
                }
            }

            public void onFinish() {
                pDialog.setTitleText("Update Success!")
                        .setConfirmText("OK")
                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                MyApplication.getInstance().count ++;
//                if(MyApplication.getInstance().count / 2 == 0){
//                    processTimeTxt.setText(StringConstant.PROCESS_TIME + "5.1s");
//                    processResultTxt.setText(StringConstant.RESULT_STRING1);
//                }
//                else {
//                    processResultTxt.setText(StringConstant.RESULT_STRING2);
//                    processTimeTxt.setText(StringConstant.PROCESS_TIME + "4.3s");
//                }
//                processState.setText(StringConstant.PROCESS_STATUS + "已处理");
            }
        }.start();
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 注册eventbus
//        EventBus.getDefault().register(this);
        // 初始化界面
        initView();
        // 初始化监听器
        initListener();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings)  {
            Intent intent = new Intent(this, SampleAlertActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                // 获取返回的图片列表
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                mSelectPath.size();
                if (mSelectPath == null || mSelectPath.size() > 1){
                    return;
                }
                else{
                    String url = mSelectPath.get(0);
                    url = "file://" + url;
                    Intent intent = new Intent(this,ProcessDetailActivity.class);
                    intent.putExtra(StringConstant.INTENT_IMG_STRING,url);
                    startActivity(intent);
                    // 获取对应的
                }
                // 处理你自己的逻辑 ....
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_STORAGE_READ_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                pickImage();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 调用系统的参数
     */
    private void pickImage() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN // Permission was added in API Level 16
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE,
                    getString(R.string.mis_permission_rationale),
                    REQUEST_STORAGE_READ_ACCESS_PERMISSION);
        } else {
            MultiImageSelector selector = MultiImageSelector.create(MainActivity.this);
            selector.showCamera(true);
            selector.count(1);
            selector.multi();
            selector.origin(mSelectPath);
            selector.start(MainActivity.this, REQUEST_IMAGE);
        }
    }

    private void requestPermission(final String permission, String rationale, final int requestCode) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.mis_permission_dialog_title)
                    .setMessage(rationale)
                    .setPositiveButton(R.string.mis_permission_dialog_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
                        }
                    })
                    .setNegativeButton(R.string.mis_permission_dialog_cancel, null)
                    .create().show();
        } else {
            ActivityCompat.requestPermissions(this, new String[]{permission}, requestCode);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
//        MyApplication.setHomeActivityStop();
//        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstKeyTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
            MyToast.makeText("再按一次退出程序");
            firstKeyTime = secondTime;// 更新firstTime
        } else { // 两次按键小于2秒时，退出应用
            if (!isExiting) {
                isExiting = true;
//                MyApplication.setGlobalData(null);
                Timer timer = new Timer();
                timer.schedule(task, 1, 10); // 1ms延迟后调用task，每隔10ms调用一次run方法
//                HttpUtil.existApp(existHandler);
//                HttpManager.setClient(null);
            }
        }
    }

    /**
     * 退出应用的计时器，由于退出时需要发送注销请求到服务器，网络不好时延迟非常大导致退不出应用
     * 解决方案：定义一个计时器，如果网络请求等待时间超过500ms，强制退出。
     */
    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            runOnUiThread(new Runnable() { // UI thread
                @Override
                public void run() {
                    if (time > 500 || readyToExit) { // 计时超过500ms或者网络请求已返回，则马上结束
                        finish();
                    } else {
                        time += 10;
                    }
                }
            });
        }
    };

    /**
     * 本地native调用字符变化
     */
    public native String stringFromJNI();

    /**
     * 调用jni输入的int数组
     *
     * @param inputArray
     * @param height
     * @param width
     * @return
     */
    public native int[] rgb2Gray(int[] inputArray, int height, int width);

}
